package com.hjy.cabinet.ws.service;

import static android.content.ContentValues.TAG;

import android.util.Log;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hjy.cabinet.ws.domain.ws.InfoBackEvent;
import com.hjy.cabinet.ws.domain.ws.WbsocketResponseBody;
import com.hjy.cabinet.ws.domain.ws.WebSocketRequest;
import com.hjy.cabinet.ws.domain.ws.WsData;

import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Random;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class WebsocketBasis {
    private OkHttpClient client = null;
    private WebSocket webSocket = null;
    private WebSocketListener listener = null;
    private Request request = null;

    private static WebsocketBasis instance;


    private WebsocketBasis() {
    }

    public static WebsocketBasis getInstance() {
        if (instance == null) {
            synchronized (WebsocketBasis.class) {
                if (instance == null) {
                    instance = new WebsocketBasis();
                }
            }
        }
        return instance;
    }

    public void connectWebSocket(String ip) {
        try {
            //判断客户端是否为空
            if (client == null) {
                client = getUnsafeOkHttpClient();
                // 创建WebSocket请求
                request = new Request.Builder()
                        .url("wss://"+ip+":9393") // 目标wss服务地址
                        .build();

                // 创建WebSocket监听器
                listener = new WebSocketListener() {
                    @Override
                    public void onOpen(WebSocket webSocket, Response response) {
                        Log.d("websocket底层", "Connected to server");
                    }

                    @Override
                    public void onMessage(WebSocket webSocket, String text) {
                        WebSocketDataHander webSocketDataHander = WebSocketDataHander.getInstance();
                        webSocketDataHander.textDeal(text);
                    }
//                }

                    @Override
                    public void onClosed(WebSocket webSocket, int code, String reason) {

                        Log.d("websocket底层", "Closed connection: " + reason);
                    }

                    @Override
                    public void onFailure(WebSocket webSocket, Throwable t, Response response) {

                        Log.e("websocket底层", "Error: " + t.getMessage());
                    }
                };
            }
            // 创建WebSocket连接
            webSocket = client.newWebSocket(request, listener);
        } catch (Exception e) {
            Log.e(TAG, "Error: " + e.getMessage(), e);
        }
    }


    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, "连接关闭");
        }
    }

    //处理证书
    public static OkHttpClient getUnsafeOkHttpClient() {
        try {
            // 创建一个信任所有证书的X509TrustManager
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                            // 空实现，信任所有证书
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                            // 空实现，信任所有证书
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };

            // 创建一个信任所有证书的SSLContext
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new SecureRandom());

            // 创建一个总是返回true的HostnameVerifier
            final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            // 创建OkHttpClient并设置SSLSocketFactory和HostnameVerifier
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(hostnameVerifier);

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public WebSocket getWebSocket() {
        return webSocket;
    }

    public void setWebSocket(WebSocket webSocket) {
        this.webSocket = webSocket;
    }
}
